package com.mo.axion.support.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @author Mo
 * @createTime 2024/2/18 15:25
 * @description 系统关闭后 延迟关闭线程池
 */
@Slf4j
@Component
public class ThreadPoolExecutorShutdownDefinition implements ApplicationListener<ContextClosedEvent> {

    /**
     * 线程中任务在家收到关闭信号等待强制终止时间，时间到后线程池则销毁
     */
    private static final long AWAIT_TERMINATION = 20;

    /**
     * AWAIT_TERMINATION 的时间单位
     */
    private static final TimeUnit TIME_UNIT = TimeUnit.SECONDS;

    /**
     * 线程池
     */
    private final List<ExecutorService> POOLS = Collections.synchronizedList(new ArrayList<>(12));

    public void registryExecutor(ExecutorService executor) {
        POOLS.add(executor);
    }

    @Override
    public void onApplicationEvent(ContextClosedEvent event) {
        log.info("容器关闭前处理线程池关闭，当前需要处理的线程数量:{}>>>>", POOLS.size());
        if (CollectionUtils.isEmpty(POOLS)) {
            return;
        }
        for (ExecutorService pool : POOLS) {
            pool.shutdown();
            try {
                if (!pool.awaitTermination(AWAIT_TERMINATION, TIME_UNIT)) {
                    log.warn("等待executor【{}】终止超时", pool);
                }
            } catch (InterruptedException e) {
                log.warn("等待executor【{}】终止超时", pool);
                Thread.currentThread().interrupt();
            }
        }
    }
}
